/*
 * www_client.c
 *
 *  Created on: 2010-6-18
 *      Author: guobc
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

int htconnect(char* domain, int port) {
	int fd;
	struct hostent* site;
	struct sockaddr_in addr;

	site = gethostbyname(domain);
	printf("host name: %s\n", site->h_addr_list[0]);
	if (site == NULL) {
		return -2;
	}

	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd < 0) {
		return -1;
	}

	memset(&addr, 0, sizeof(struct sockaddr_in));
	memcpy(&addr.sin_addr, site->h_addr_list[0], site->h_length);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);

	return connect(fd, (struct sockaddr*) &addr, sizeof(struct sockaddr)) < 0 ? 1 : fd;
}

int htsend(int sock, char* fmt, ...){
	char BUF[1024];
	va_list argptr;
	va_start(argptr, fmt);
	vsprintf(BUF, fmt, argptr);
	va_end(argptr);
	return send(sock, BUF, strlen(BUF), 0);
}

int main(int argc, char** argv){
	int fd;
	char bugs_bunny[3];
	if(argc < 2){
		printf("Usage: www_client host\n");
		return 0;
	}

	fd = htconnect(argv[1], 80);
	if(fd < 0){
		printf("Socket connect error!\n");
		return 0;
	}

	htsend(fd, "GET /HTTP/1.0%c", 10);
	htsend(fd, "HOST: %s%c", argv[1], 10);
	htsend(fd, "%c", 10);
	while(read(fd, bugs_bunny, 1) > 0){
		printf("%c", bugs_bunny[0]);
	}
	close(fd);
	return 0;
}
